<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Python装饰器，就是这么强大！.md |  
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-develop/Python装饰器，就是这么强大！"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Python装饰器，就是这么强大！.md
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/11/11/develop/Python%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%8C%E5%B0%B1%E6%98%AF%E8%BF%99%E4%B9%88%E5%BC%BA%E5%A4%A7%EF%BC%81/" class="article-date">
  <time datetime="2020-11-10T16:00:00.000Z" itemprop="datePublished">2020-11-11</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/develop/">develop</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">1.8k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">7 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="Python装饰器，就是这么强大"><a href="#Python装饰器，就是这么强大" class="headerlink" title="Python装饰器，就是这么强大"></a>Python装饰器，就是这么强大</h1><h3 id="1-装饰器的定义"><a href="#1-装饰器的定义" class="headerlink" title="1. 装饰器的定义"></a>1. 装饰器的定义</h3><p>就是给已有函数增加额外功能的函数，它本质上就是一个闭包函数。装饰器的功能特点:</p>
<p>1、不修改已有函数的源代码</p>
<p>2、不修改已有函数的调用方式</p>
<p>3、给已有函数增加额外的功能</p>
<p>4、闭包和装饰器的区分：</p>
<p>如果闭包函数的参数有且只有一个，并且是函数类型，那么这个闭包函数称之为装饰器。写代码要遵循开放封闭原则，它规定已经实现的功能代码不允许被修改，但可以被扩展。</p>
<h3 id="2-装饰器的示例代码"><a href="#2-装饰器的示例代码" class="headerlink" title="2. 装饰器的示例代码"></a>2. 装饰器的示例代码</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"># 定义装饰器  </span><br><span class="line">def decorator(func):  </span><br><span class="line">    def inner():  </span><br><span class="line">        # 在内部函数里面对已有函数进行装饰  </span><br><span class="line">        print(&#39;已添加登录认证&#39;)  </span><br><span class="line">        func()  </span><br><span class="line">    return inner  </span><br><span class="line">  </span><br><span class="line">def comment():  </span><br><span class="line">    print(&#39;发表评论&#39;)  </span><br><span class="line"># 调用装饰器对已有函数进行装饰，左边的comment&#x3D;inner  </span><br><span class="line">comment &#x3D; decorator(comment)  </span><br><span class="line"># 调用方式不变  </span><br><span class="line">comment()  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="3-装饰器的语法糖写法"><a href="#3-装饰器的语法糖写法" class="headerlink" title="3. 装饰器的语法糖写法"></a>3. 装饰器的语法糖写法</h3><p>如果有多个函数都需要添加登录验证的功能，每次都需要编写func = decorator(func)这样代码对已有函数进行装饰，这种做法还是比较麻烦。</p>
<p>Python给提供了一个装饰函数更加简单的写法，那就是语法糖，语法糖的书写格式是: @装饰器名字，通过语法糖的方式也可以完成对已有函数的装饰。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"># 定义装饰器  </span><br><span class="line">def decorator(func):  </span><br><span class="line">    def inner():  </span><br><span class="line">        # 在内部函数里面对已有函数进行装饰  </span><br><span class="line">        print(&#39;已添加登录认证&#39;)  </span><br><span class="line">        func()  </span><br><span class="line">    return inner  </span><br><span class="line">  </span><br><span class="line">@decorator  # comment &#x3D; decorator(comment) 装饰器语法糖对该代码进行了封装 左边comment&#x3D;inner  </span><br><span class="line">def comment():  </span><br><span class="line">    print(&#39;发表评论&#39;)  </span><br><span class="line"># 调用方式不变  </span><br><span class="line">comment()  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4-装饰器的执行时机"><a href="#4-装饰器的执行时机" class="headerlink" title="4. 装饰器的执行时机"></a>4. 装饰器的执行时机</h3><p>当前模块加载完成以后，装饰器会立即执行，对已有函数进行装饰。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"># 定义装饰器  </span><br><span class="line">def decorator(func):  </span><br><span class="line">    print(&#39;装饰器执行了&#39;)  </span><br><span class="line">    def inner():  </span><br><span class="line">        # 在内部函数里面对已有函数进行装饰  </span><br><span class="line">        print(&#39;已添加登录认证&#39;)  </span><br><span class="line">        func()  </span><br><span class="line">    return inner  </span><br><span class="line">  </span><br><span class="line">@decorator  # comment &#x3D; decorator(comment) 装饰器语法糖对该代码进行了封装 左边comment&#x3D;inner  </span><br><span class="line">def comment():  </span><br><span class="line">    print(&#39;发表评论&#39;)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="5-装饰器的使用"><a href="#5-装饰器的使用" class="headerlink" title="5. 装饰器的使用"></a>5. 装饰器的使用</h3><h4 id="5-1-装饰器的使用场景"><a href="#5-1-装饰器的使用场景" class="headerlink" title="5.1 装饰器的使用场景"></a>5.1 装饰器的使用场景</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">1.函数执行时间的统计。  </span><br><span class="line">  </span><br><span class="line">2.输出日志信息。  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="5-2-装饰器实现已有函数执行时间的统计"><a href="#5-2-装饰器实现已有函数执行时间的统计" class="headerlink" title="5.2 装饰器实现已有函数执行时间的统计"></a>5.2 装饰器实现已有函数执行时间的统计</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">import time  </span><br><span class="line">  </span><br><span class="line">def decorator(func):  </span><br><span class="line">    def inner():  </span><br><span class="line">        # 获取时间距离1970-1-1 0:0:1的时间差  </span><br><span class="line">        begin &#x3D; time.time()  </span><br><span class="line">        func()  </span><br><span class="line">        end &#x3D; time.time()  </span><br><span class="line">        result &#x3D; end - begin  </span><br><span class="line">        print(f&#39;函数执行完成耗时：&#123;result&#125;&#39;)  </span><br><span class="line">    return inner  </span><br><span class="line">  </span><br><span class="line">@decorator  </span><br><span class="line">def work():  </span><br><span class="line">    for i in range(10000):  </span><br><span class="line">        print(i)  </span><br><span class="line">          </span><br><span class="line">work()  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="6-通用装饰器的使用"><a href="#6-通用装饰器的使用" class="headerlink" title="6. 通用装饰器的使用"></a>6. 通用装饰器的使用</h3><p>通用装饰器：可以装饰任意类型的函数。使用装饰器装饰已有函数的时候，内部函数的类型和要装饰的已有函数的类型保持一致。</p>
<h4 id="6-1-装饰带有参数的函数"><a href="#6-1-装饰带有参数的函数" class="headerlink" title="6.1 装饰带有参数的函数"></a>6.1 装饰带有参数的函数</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">def decorator(func):  </span><br><span class="line">    def inner(num1, num2):  </span><br><span class="line">        print(&#39;正在努力执行加法计算&#39;)  </span><br><span class="line">        func(num1, num2)  </span><br><span class="line">    return inner  </span><br><span class="line">  </span><br><span class="line">@decorator  </span><br><span class="line">def add_num(num1, num2):  </span><br><span class="line">    result &#x3D; num1 + num2  </span><br><span class="line">    print(f&#39;结果为：&#123;result&#125;&#39;)  </span><br><span class="line">  </span><br><span class="line">add_num(1, 2)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="6-2-装饰带有参数、返回值的函数"><a href="#6-2-装饰带有参数、返回值的函数" class="headerlink" title="6.2 装饰带有参数、返回值的函数"></a>6.2 装饰带有参数、返回值的函数</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">def decorator(func):  </span><br><span class="line">    def inner(num1, num2):  </span><br><span class="line">        print(&#39;正在努力执行加法计算&#39;)  </span><br><span class="line">        num &#x3D; func(num1, num2)  </span><br><span class="line">        return num  </span><br><span class="line">    return inner  </span><br><span class="line">  </span><br><span class="line">@decorator  </span><br><span class="line">def add_num(num1, num2):  </span><br><span class="line">    result &#x3D; num1 + num2  </span><br><span class="line">    return result  </span><br><span class="line">  </span><br><span class="line">result &#x3D; add_num(1, 2)  </span><br><span class="line">print(f&#39;结果为：&#123;result&#125;&#39;)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="6-3-装饰带有不定长参数、返回值的函数"><a href="#6-3-装饰带有不定长参数、返回值的函数" class="headerlink" title="6.3 装饰带有不定长参数、返回值的函数"></a>6.3 装饰带有不定长参数、返回值的函数</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">def decorator(func):  </span><br><span class="line">    def inner(*args, **kwargs):  </span><br><span class="line">        print(&#39;正在努力执行加法计算&#39;)  </span><br><span class="line">        # *args:把元组里面的每一个元素，按照位置参数的方式进行传参  </span><br><span class="line">        # **kwargs:把字典里面的每一个键值对，按照关键字的方式进行传参  </span><br><span class="line">        num &#x3D; func(*args, **kwargs)  </span><br><span class="line">        return num  </span><br><span class="line">    return inner  </span><br><span class="line">  </span><br><span class="line">@decorator  </span><br><span class="line">def add_num(*args, **kwargs):  </span><br><span class="line">    result &#x3D; 0  </span><br><span class="line">    for value in args:  </span><br><span class="line">        result +&#x3D; value  </span><br><span class="line">    for value in kwargs.values():  </span><br><span class="line">        result +&#x3D; value  </span><br><span class="line">    return result  </span><br><span class="line">  </span><br><span class="line">result &#x3D; add_num(1, 2, a&#x3D;3)  </span><br><span class="line">print(f&#39;结果为：&#123;result&#125;&#39;)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="7-多个装饰器的使用"><a href="#7-多个装饰器的使用" class="headerlink" title="7. 多个装饰器的使用"></a>7. 多个装饰器的使用</h3><p>多个装饰器的装饰过程：由内到外的一个装饰过程，先执行内部的装饰器，在执行外部的装饰器。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">def make_div(func):  </span><br><span class="line">    print(&#39;make_div装饰器执行了&#39;)  </span><br><span class="line">  </span><br><span class="line">    def inner():  </span><br><span class="line">        result &#x3D; &#39;&lt;div&gt;&#39; + func() + &#39;&lt;&#x2F;div&gt;&#39;  </span><br><span class="line">        return result  </span><br><span class="line">    return inner  </span><br><span class="line">  </span><br><span class="line">def make_p(func):  </span><br><span class="line">    print(&#39;make_p装饰器执行了&#39;)  </span><br><span class="line">  </span><br><span class="line">    def inner():  </span><br><span class="line">        result &#x3D; &#39;&lt;p&gt;&#39; + func() + &#39;&lt;&#x2F;p&gt;&#39;  </span><br><span class="line">        return result  </span><br><span class="line">    return inner  </span><br><span class="line"># 原理剖析：content &#x3D; make_div(make_p(content))  </span><br><span class="line"># 分布拆解：content &#x3D; make_p(content)，内部装饰器完成，content &#x3D; make_p.inner  </span><br><span class="line">#          content &#x3D; make_div(make_p.inner)  </span><br><span class="line">@make_div  </span><br><span class="line">@make_p  </span><br><span class="line">def content():  </span><br><span class="line">    return &#39;人生苦短，我用python&#39;  </span><br><span class="line">  </span><br><span class="line">c &#x3D; content()  </span><br><span class="line">print(c)  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">make_p装饰器执行了  </span><br><span class="line">  </span><br><span class="line">make_div装饰器执行了  </span><br><span class="line">  </span><br><span class="line">&lt;div&gt;&lt;p&gt;人生苦短，我用python&lt;&#x2F;p&gt;&lt;&#x2F;div&gt;  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="8-带有参数的装饰器"><a href="#8-带有参数的装饰器" class="headerlink" title="8. 带有参数的装饰器"></a>8. 带有参数的装饰器</h3><p>带有参数的装饰器就是使用装饰器装饰函数的时候可以传入指定参数，语法格式: @装饰器(参数,…)。使用带有参数的装饰器，其实是在装饰器外面又包裹了一个函数，使用该函数接收参数，返回是装饰器，因为 @ 符号需要配合装饰器实例使用。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">def return_decorator(flag):  </span><br><span class="line">    # 装饰器只能接收一个参数并且是函数类型  </span><br><span class="line">    def decorator(func):  </span><br><span class="line">        def inner(a, b):  </span><br><span class="line">            if flag &#x3D;&#x3D; &#39;+&#39;:  </span><br><span class="line">                print(&#39;正在努力执行加法计算&#39;)  </span><br><span class="line">            elif flag &#x3D;&#x3D; &#39;-&#39;:  </span><br><span class="line">                print(&#39;正在努力执行减法计算&#39;)  </span><br><span class="line">            func(a, b)  </span><br><span class="line">        return inner  </span><br><span class="line">    # 当调用函数的时候可以返回一个装饰器decorato  </span><br><span class="line">    return decorator  </span><br><span class="line">  </span><br><span class="line">@return_decorator(&#39;+&#39;)  # decorator &#x3D; return_decorator(&#39;+&#39;), @decorator &#x3D;&gt; add_num &#x3D; decorator(add_num)  </span><br><span class="line">def add_num(a, b):  </span><br><span class="line">    result &#x3D; a + b  </span><br><span class="line">    print(result)  </span><br><span class="line">      </span><br><span class="line">@return_decorator(&#39;-&#39;)  </span><br><span class="line">def sub_num(a, b):  </span><br><span class="line">    result &#x3D; a - b  </span><br><span class="line">    print(result)  </span><br><span class="line">  </span><br><span class="line">add_num(1, 2)  </span><br><span class="line">sub_num(1, 2)  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="9-类装饰器的使用"><a href="#9-类装饰器的使用" class="headerlink" title="9. 类装饰器的使用"></a>9. 类装饰器的使用</h3><p>类装饰器：使用类装饰已有函数</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">class MyDecorator(object):  </span><br><span class="line">    def __init__(self, func):  </span><br><span class="line">        self.__func &#x3D; func  </span><br><span class="line">  </span><br><span class="line">    # 实现__call__方法，表示对象是一个可调用对象，可以像调用函数一样进行调用  </span><br><span class="line">    def __call__(self, *args, **kwargs):  </span><br><span class="line">        # 对已有函数进行封装  </span><br><span class="line">        print(&#39;马上就有下班啦&#39;)  </span><br><span class="line">        self.__func()  </span><br><span class="line">@MyDecorator  # @MyDecorator &#x3D;&gt; show &#x3D; MyDecorator(show)  </span><br><span class="line">def show():  </span><br><span class="line">    print(&#39;快要下雪啦&#39;)  </span><br><span class="line"># 执行show，就相当于执行MyDecorator类创建的实例对象，show() &#x3D;&gt; 对象()  </span><br><span class="line">show()  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">马上就有下班啦  </span><br><span class="line">  </span><br><span class="line">快要下雪啦  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="扩展："><a href="#扩展：" class="headerlink" title="扩展："></a>扩展：</h4><p>函数之所以能够调用，是因为函数内部实现了 <strong>call</strong> 方法。</p>
<h3 id="10-装饰器应用场景"><a href="#10-装饰器应用场景" class="headerlink" title="10. 装饰器应用场景"></a>10. 装饰器应用场景</h3><p>1、收集函数的操作或错误日志记录。</p>
<p>2、验证函数的使用权限。</p>
<p>3、计算函数的运行时间。</p>
<p>4、在ORM/DB模型操作时，通过属性方法动态地获取关联的数据。</p>
<p>5、函数数据的缓存。</p>
<p>6、定制函数的输入和输出（序列化和反序列化）。</p>
<p>_原文来自：<a target="_blank" rel="noopener" href="https://blog.csdn.net/mall/_lucy/article/details/108791699">https://blog.csdn.net/mall\_lucy/article/details/108791699</a><br>作者：南枝向暖北枝寒MA</p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2020/11/11/develop/Python%E8%A3%85%E9%A5%B0%E5%99%A8%EF%BC%8C%E5%B0%B1%E6%98%AF%E8%BF%99%E4%B9%88%E5%BC%BA%E5%A4%A7%EF%BC%81/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/develop/" rel="tag">develop</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/11/11/develop/Python%20%E7%82%AB%E6%8A%80%E6%93%8D%E4%BD%9C%EF%BC%9A%E6%A8%A1%E5%9D%97%E9%87%8D%E8%BD%BD%E7%9A%84%E4%BA%94%E7%A7%8D%E6%96%B9%E6%B3%95/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Python 炫技操作：模块重载的五种方法.md
          
        </div>
      </a>
    
    
      <a href="/2020/11/11/develop/%E4%B8%80%E6%96%87%E7%9C%8B%E6%87%82Python%E5%88%97%E8%A1%A8%E3%80%81%E5%85%83%E7%BB%84%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%93%8D%E4%BD%9C/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">一文看懂Python列表、元组和字符串操作.md</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> TzWind
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Hexo"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" target="_blank" rel="noopener" href="http://www.baidu.com">百度</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2019/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>